<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import ContractShow from './component/ContractShow.vue'

// 创建axios实例
const api = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 5000
})

const contractShowRef = ref()

// 搜索参数
const searchParams = ref({
  contractNumber: '',
  contractName: '',
  dateRange: []
})

// 分页参数
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const loading = ref(false)
const showChangeCompare = ref(false)
const currentRecord = ref(null)

// 从后端获取的变更记录
const historyRecords = ref([])

// 字段映射表
const fieldMap = {
  title: '合同名称',
  applicant: '申请人',
  companyName: '企业名称',
  contractType: '合同类型',
  startDate: '生效日期',
  endDate: '到期日期',
  contractStatus: '合同状态',
  companyAddress: '企业地址',
  changeReason: '变更原因'
}

// API调用方法
const contractHistoryApi = {
  // 获取所有变更记录
  getAllHistory: async () => {
    const response = await api.get('/api/contract-change-history')
    return response.data
  },
  
  // 条件搜索变更记录
  search: async (params) => {
    const response = await api.post('/api/contract-change-history/search', params)
    return response.data
  },
  
  // 根据ID查询变更记录
  getById: async (id) => {
    const response = await api.get(`/api/contract-change-history/${id}`)
    return response.data
  },
  
  // 根据合同ID查询变更记录
  getByContractId: async (contractId) => {
    const response = await api.get(`/api/contract-change-history/contract/${contractId}`)
    return response.data
  },
  
  // 根据合同编号查询变更记录
  getByContractNumber: async (contractNumber) => {
    const response = await api.get(`/api/contract-change-history/contract-number/${contractNumber}`)
    return response.data
  },
  
  // 添加变更记录
  addChangeHistory: async (history) => {
    const response = await api.post('/api/contract-change-history', history)
    return response.data
  },
  
  // 根据合同ID删除变更记录
  deleteByContractId: async (contractId) => {
    const response = await api.delete(`/api/contract-change-history/contract/${contractId}`)
    return response.data
  }
}

// 加载变更记录数据
const loadHistoryData = async () => {
  try {
    loading.value = true
    console.log('开始加载变更记录数据...')
    
    const response = await contractHistoryApi.getAllHistory()
    console.log('API响应:', response)
    
    if (response && response.success) {
      historyRecords.value = response.data || []
      console.log('成功加载变更记录:', historyRecords.value.length, '条')
      
      // 查看所有记录
      historyRecords.value.forEach((record, index) => {
        console.log(`记录 ${index + 1}:`, record)
      })
      
      if (historyRecords.value.length === 0) {
        ElMessage.info('暂无变更记录数据')
      }
    } else {
      console.error('API返回失败:', response)
      ElMessage.error(response?.message || '获取变更记录失败')
      historyRecords.value = []
    }
  } catch (error) {
    console.error('加载变更记录失败:', error)
    ElMessage.error('加载变更记录失败: ' + (error.message || '网络错误'))
    historyRecords.value = []
  } finally {
    loading.value = false
  }
}

// 条件搜索
const searchHistory = async () => {
  try {
    loading.value = true
    console.log('开始搜索:', searchParams.value)
    
    const params = {
      contractNumber: searchParams.value.contractNumber,
      contractName: searchParams.value.contractName
    }
    
    // 时间范围添加到参数中
    if (searchParams.value.dateRange && searchParams.value.dateRange.length === 2) {
      params.startDate = searchParams.value.dateRange[0]
      params.endDate = searchParams.value.dateRange[1]
    }
    
    console.log('搜索参数:', params)
    const response = await contractHistoryApi.search(params)
    console.log('搜索响应:', response)
    
    if (response && response.success) {
      historyRecords.value = response.data || []
      pagination.value.currentPage = 1
      ElMessage.success(`搜索到 ${historyRecords.value.length} 条记录`)
    } else {
      ElMessage.error(response?.message || '搜索失败')
    }
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败: ' + (error.message || '网络错误'))
  } finally {
    loading.value = false
  }
}

// 获取所有记录
const allRecords = computed(() => {
  const records = historyRecords.value.map(record => ({
    ...record,
    contractName: record.contractName || record.currentData?.title || '未知合同',
    timestamp: record.changedAt,
    data: record.currentData || {},
    previousData: record.previousData || null,
    // 添加actionType的中文显示
    actionTypeText: getActionTypeText(record.actionType)
  }))
  
  console.log('处理后的所有记录:', records)
  return records
})

// 获取actionType的中文显示
const getActionTypeText = (actionType) => {
  const actionTypeStr = String(actionType).toUpperCase()
  switch (actionTypeStr) {
    case 'CREATE':
    case '1':
      return '创建'
    case 'UPDATE': 
    case '2':
      return '修改'
    case 'DELETE':
    case '3':
      return '删除'
    default:
      return actionType
  }
}

// 获取actionType的标签类型
const getActionTypeTagType = (actionType) => {
  const actionTypeStr = String(actionType).toUpperCase()
  switch (actionTypeStr) {
    case 'CREATE':
    case '1':
      return 'success' // 绿色
    case 'UPDATE':
    case '2':
      return 'warning' // 黄色
    case 'DELETE':
    case '3':
      return 'danger' // 红色
    default:
      return 'info' // 蓝色
  }
}

// 筛选后的记录
const filteredRecords = computed(() => {
  let records = allRecords.value
  console.log('开始筛选，原始记录数:', records.length)

  // 按合同编号筛选
  if (searchParams.value.contractNumber) {
    records = records.filter(record => 
      record.contractNumber && record.contractNumber.includes(searchParams.value.contractNumber)
    )
  }

  // 按合同名称筛选
  if (searchParams.value.contractName) {
    records = records.filter(record => 
      record.contractName && record.contractName.includes(searchParams.value.contractName)
    )
  }

  // 按时间范围筛选
  if (searchParams.value.dateRange && searchParams.value.dateRange.length === 2) {
    const [startDate, endDate] = searchParams.value.dateRange
    records = records.filter(record => {
      if (!record.timestamp) return false
      const recordDate = record.timestamp.split('T')[0]
      return recordDate >= startDate && recordDate <= endDate
    })
  }

  console.log('筛选后记录数:', records.length)
  return records
})

// 表格数据（分页后）
const tableData = computed(() => {
  const start = (pagination.value.currentPage - 1) * pagination.value.pageSize
  const end = start + pagination.value.pageSize
  pagination.value.total = filteredRecords.value.length
  
  const data = filteredRecords.value.slice(start, end)
  console.log('分页后数据:', data)
  return data
})

// 获取变更字段数量
const getChangedFieldsCount = (record) => {
  // 对于创建类型的记录，显示"新增合同"
  if (!record.previousData || Object.keys(record.previousData).length === 0) {
    return record.actionType === 'CREATE' || record.actionType === '1' ? '新增合同' : '首次修改'
  }
  
  const changedFields = Object.keys(fieldMap).filter(field => {
    const oldValue = record.previousData[field]
    const newValue = record.data[field]
    return oldValue !== newValue
  })
  
  return changedFields.length > 0 ? `${changedFields.length}个字段` : '无变更'
}

// 变更对比数据
const changeFields = computed(() => {
  if (!currentRecord.value) return []
  
  const fields = []
  
  // 创建操作，显示所有字段为新增
  const actionType = String(currentRecord.value.actionType).toUpperCase()
  if (actionType === 'CREATE' || actionType === '1') {
    Object.keys(fieldMap).forEach(field => {
      const newValue = currentRecord.value.data[field]
      if (newValue !== null && newValue !== undefined && newValue !== '') {
        fields.push({
          field,
          fieldName: fieldMap[field],
          oldValue: '空',
          newValue: formatFieldValue(field, newValue),
          isNew: true
        })
      }
    })
  } 
  //修改操作，显示变更的字段
  else if (!currentRecord.value.previousData || Object.keys(currentRecord.value.previousData).length === 0) {
    Object.keys(fieldMap).forEach(field => {
      const newValue = currentRecord.value.data[field]
      if (newValue !== null && newValue !== undefined && newValue !== '') {
        fields.push({
          field,
          fieldName: fieldMap[field],
          oldValue: '空',
          newValue: formatFieldValue(field, newValue),
          isNew: true
        })
      }
    })
  } else {
    // 后续修改，显示变更的字段
    Object.keys(fieldMap).forEach(field => {
      const oldValue = currentRecord.value.previousData[field]
      const newValue = currentRecord.value.data[field]
      
      if (oldValue !== newValue) {
        fields.push({
          field,
          fieldName: fieldMap[field],
          oldValue: formatFieldValue(field, oldValue),
          newValue: formatFieldValue(field, newValue),
          isNew: false
        })
      }
    })
  }
  
  console.log('变更字段:', fields)
  return fields
})

// 格式化字段值
const formatFieldValue = (field, value) => {
  if (value === null || value === undefined || value === '') return '空'
  
  // 日期字段特殊处理
  if (field === 'startDate' || field === 'endDate') {
    return value ? new Date(value).toLocaleDateString() : '空'
  }
  
  return String(value)
}

// 格式化日期时间
const formatDateTime = (timestamp) => {
  if (!timestamp) return ''
  try {
    const date = new Date(timestamp)
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
  } catch (error) {
    return timestamp
  }
}

// 查看合同详情
const onViewContractDetail = (record) => {
  console.log('查看合同详情:', record)
  contractShowRef.value.open(record.data)
}

// 查看变更对比
const onViewChanges = (record) => {
  console.log('查看变更对比:', record)
  currentRecord.value = record
  showChangeCompare.value = true
}

// 搜索
const onSearch = () => {
  console.log('执行搜索')
  searchHistory()
}

// 重置
const onReset = () => {
  console.log('执行重置')
  searchParams.value = {
    contractNumber: '',
    contractName: '',
    dateRange: []
  }
  loadHistoryData()
}

// 分页大小变化
const onSizeChange = (size) => {
  console.log('分页大小变化:', size)
  pagination.value.pageSize = size
  pagination.value.currentPage = 1
}

// 当前页变化
const onCurrentChange = (page) => {
  console.log('当前页变化:', page)
  pagination.value.currentPage = page
}

// 初始化
onMounted(() => {
  console.log('合同变更记录页面加载完成')
  loadHistoryData()
})
</script>

<template>
  <div class="contract-history">
    <!-- 标题和分割线 -->
    <div class="header-section">
      <h1 class="contract-title">合同变更记录</h1>
      <div class="divider"></div>
    </div>

    <!-- 搜索区域 -->
    <el-form inline style="display: flex; justify-content: space-between; align-items: center; width: 100%; margin-bottom: 20px;">
      <div style="display: flex; flex-wrap: wrap; gap: 10px;">
        <el-form-item label="合同编号">
          <el-input v-model="searchParams.contractNumber" placeholder="输入合同编号" clearable style="width: 150px"></el-input>
        </el-form-item>
        
        <el-form-item label="合同名称">
          <el-input v-model="searchParams.contractName" placeholder="输入合同名称" clearable style="width: 150px"></el-input>
        </el-form-item>
        
        <el-form-item label="变更时间">
          <el-date-picker
            v-model="searchParams.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button @click="onSearch" type="primary">查询</el-button>
          <el-button @click="onReset">重置</el-button>
        </el-form-item>
      </div>
    </el-form>

    <!-- 变更记录表格 -->
    <el-table 
      :data="tableData" 
      v-loading="loading"
      border
      style="width: 100%"
    >
      <el-table-column type="index" label="序号" width="80" fixed></el-table-column>
      <el-table-column label="变更时间" prop="timestamp" width="180">
        <template #default="{ row }">
          {{ formatDateTime(row.timestamp) }}
        </template>
      </el-table-column>
      <el-table-column label="合同编号" prop="contractNumber" width="150"></el-table-column>
      <el-table-column label="合同名称" prop="contractName" min-width="200"></el-table-column>
      <el-table-column label="变更类型" prop="actionType" width="120">
        <template #default="{ row }">
          <el-tag :type="getActionTypeTagType(row.actionType)">
            {{ row.actionTypeText }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="变更字段数" width="120">
        <template #default="{ row }">
          {{ getChangedFieldsCount(row) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="onViewContractDetail(row)">合同详情</el-button>
          <el-button size="small" type="primary" @click="onViewChanges(row)">变更对比</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <el-pagination
      v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total"
      @size-change="onSizeChange"
      @current-change="onCurrentChange"
      style="margin-top: 20px; justify-content: flex-end;"
    />

    <!-- 合同详情弹窗 -->
    <contract-show ref="contractShowRef"></contract-show>

    <!-- 变更对比弹窗 -->
    <el-dialog v-model="showChangeCompare" :title="`变更对比 - ${currentRecord?.contractNumber || ''}`" width="80%">
      <div v-if="currentRecord" class="change-compare-content">
        <div class="change-info">
          <div class="info-item">
            <span class="info-label">合同编号：</span>
            <span class="info-value">{{ currentRecord.contractNumber }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">合同名称：</span>
            <span class="info-value">{{ currentRecord.contractName }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">变更时间：</span>
            <span class="info-value">{{ formatDateTime(currentRecord.timestamp) }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">变更类型：</span>
            <span class="info-value">{{ currentRecord.actionTypeText }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">变更原因：</span>
            <span class="info-value">{{ currentRecord.changeReason || '无' }}</span>
          </div>
        </div>

        <div class="changes-section">
          <h3>变更内容对比</h3>
          <el-table :data="changeFields" border style="width: 100%">
            <el-table-column label="字段" prop="field" width="150"></el-table-column>
            <el-table-column label="字段说明" prop="fieldName" width="150"></el-table-column>
            <el-table-column label="变更前" prop="oldValue">
              <template #default="{ row }">
                <span class="old-value">{{ row.oldValue || '空' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="变更后" prop="newValue">
              <template #default="{ row }">
                <span class="new-value">{{ row.newValue || '空' }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="showChangeCompare = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.contract-history {
  padding: 20px;
  font-family: 'Arial', sans-serif;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header-section {
  margin-bottom: 30px;
}

.contract-title {
  font-size: 20px;
  color: #333;
  margin-bottom: 10px;
  text-align: left;
}

.divider {
  height: 1px;
  background-color: #e0e0e0;
  width: 100%;
}

.change-compare-content {
  padding: 10px;
}

.change-info {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.info-item {
  display: flex;
  align-items: center;
}

.info-label {
  font-weight: bold;
  color: #555;
  margin-right: 8px;
}

.info-value {
  color: #333;
}

.changes-section {
  margin-top: 20px;
}

.changes-section h3 {
  color: #333;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e0e0e0;
}

.old-value {
  color: #f56c6c;
  text-decoration: line-through;
  background-color: #fef0f0;
  padding: 2px 6px;
  border-radius: 3px;
}

.new-value {
  color: #67c23a;
  background-color: #f0f9eb;
  padding: 2px 6px;
  border-radius: 3px;
}
</style>